package com.paypalpay.controller.common;

import com.alibaba.fastjson.JSONObject;
import com.paypalpay.pojo.Constant;
import com.paypalpay.service.DevicePartnerAccessService;
import com.paypalpay.util.wx.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;


/**
 * 对策力提供的接口
 *
 * @author lm
 *
 */
@Controller
@RequestMapping("/celi")
@Api(description = "通用接口")
public class CeliController {

	@Autowired
	private HttpSession session;

    @Autowired
	DevicePartnerAccessService devicePartnerAccessService;
	// 常量
	private String partnerCodes = "P000036";

	private String tokens = "E0A04BB5B2B71754BC8B3FC2F99D0A73";

	//Channel access package interface

	/***
	 * 合作伙伴统一的请求接口入口
	 * @param requestStr
	 * @return
	 */
//	@ApiOperation(value = "合作伙伴统一的请求接口入口")
//	@RequestMapping(value = "/getPackageList", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
//	public String channelAccessPackageInterface(@ApiParam(name = "param",value = "username:用户名;pwd:密码=={\"userName\":\"liumin\",\"pwd\":\"123456\"}")@RequestBody String requestStr) {
//
//		System.out.println("前端请求报文是：" + requestStr);
//		// 1，生成流水号
//		//String ConnSeqNo = sequenceService.getPackageTaskNo();
//		// 2,生成当前时间戳
//		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		String createTime = df.format(new Date());
//
//		RequestChannelAccess requestChannelAccess = JSONArray.parseObject(requestStr, RequestChannelAccess.class);
//
//		String requestSign = requestChannelAccess.getSign();
//		System.out.println("请求的签名是：" + requestSign);
//
//		//获取到要用的参数
//		com.paypalpay.entity.channelaccess.Data requestData=requestChannelAccess.getData();
//		String connSeqNo=requestData.getConnSeqNo();
//		String token=requestData.getToken();
//		String partnerCode = requestData.getPartnerCode();
//		String tradeTime =requestData.getTradeTime();
//		String deviceId = requestData.getTradeData().getDeviceId();
//		String deviceType = requestData.getTradeData().getDeviceType();
//
//		// 将请求体json转成String
//		String str = JSON.toJSONString(requestData);
//
//		UtilsInterfacesPackage utils = new UtilsInterfacesPackage();
//		// 将Str拿去计算签名
//		String sign = utils.calculateSignature(str);
//
//		System.out.println("计算的签名是：" + sign);
//
//		if (deviceId == null || deviceId.length() <= 0 || deviceType == null || deviceType.length() <= 0) {
//			//参数不全,回复报文
//			String jsonString = utils.partnerParamNotComplete(connSeqNo, tradeTime, partnerCode, token,deviceId,deviceType);
//			return jsonString;
//		} else {
//			//参数是齐全的
//			// 验证签名：
//			if (!requestSign.equalsIgnoreCase(sign)) {
//				// 如果收到的签名跟算出的签名相同才可以回复正确的报文
//				String jsonString = utils.signatureFailMessage(connSeqNo, tradeTime, partnerCode, token, deviceId,deviceType);
//				return jsonString;
//
//			} else {
//				//签名通过
//				//将合作伙伴访问的记录保存下来
//				DevicePartnerAccess access=new DevicePartnerAccess();
//				access.setConnSeqNo(connSeqNo);
//				access.setToken(token);
//				access.setPartnerCode(partnerCode);
//				access.setDeviceId(deviceId);
//				access.setDeviceType(deviceType);
//				access.setTradeTime(tradeTime);
//				access.setSign(requestSign);
//
//				devicePartnerAccessService.putInPartnerAccessInfo(access);
//
//				session.setAttribute("deviceId",deviceId);
//				session.setAttribute("deviceType",deviceType);
//
//				//return "redirect:http://wx.lizhisim.com/#/";
//				return  null;
//
//			}
//		}
//	}

	/*
	 * 原来的接口
	 */
	// @RequestMapping(value="getPackageList",method=RequestMethod.GET)
	// public String getPackageList(@RequestParam("imei") String
	// imei,HttpServletRequest request){
	// if(null == imei || true == imei.isEmpty() || 15 != imei.length()){
	// request.setAttribute(Constant.ERROR_CODE, Constant.EC_PARAM);
	// return "errorPage";
	// }else{
	// return "forward:/module/syncModulePackages";
	// }
	// }

	/**
	 * 获取设备套餐列表
	 *
	 * @param
	 * @return
	 */
	// http://localhost/moduleBusiness/celi/getPackageList?partnerCode=P000036&token=E0A04BB5B2B71754BC8B3FC2F99D0A73&deviceId=862822030093109&tradeTime%20=2016-03-07%2011:05:24&sign=bee0dca5a9e834654fe0ff6facfaffb8
	@ApiOperation(value = "获取设备套餐列表")
	@RequestMapping(value = "/getPackageLists", method = RequestMethod.GET)
	public String getPackageList(HttpServletRequest request, HttpServletResponse response) {
		// 将请求中的参数取出来，验证
		String deviceId=request.getParameter("deviceId");
		String deviceType=request.getParameter("deviceType");
		String tradeTime = request.getParameter("tradeTime");
		String token = request.getParameter("token");
		String partnerCode = request.getParameter("partnerCode");
		String requestSign = request.getParameter("sign");
		String sign = requestSign(partnerCode, token, tradeTime, deviceId);
		// 验证sign值是否相同
		if (requestSign.equals(sign)) {
			// 判断partnerCode，token是否相同
			if (partnerCodes.equalsIgnoreCase(partnerCode)|| tokens.equals(token)) {
				  // 验证imei号的合法性
				if (null == deviceId || true == deviceId.isEmpty()|| 20 != deviceId.length()) {
					request.setAttribute(Constant.ERROR_CODE, Constant.EC_PARAM);
					request.setAttribute("tradeRstMessage", "IMEI不合法");
					return "errorPage";
				} else {
					session.setAttribute("deviceId",deviceId);
					session.setAttribute("deviceType",deviceType);
					//return "forward:/module/syncModulePackages";
					/***
					 * 实际项目应该要在这边重定向到新版的商城
					 */
					return "redirect:http://wx.lizhisim.com/#/";
			}
			} else {
				// partnerCode或者token有误
				request.setAttribute(Constant.ERROR_CODE, Constant.EC_PARAM);
				request.setAttribute("tradeRstMessage", "partnerCode或者token有误");
				return "errorPage";
			}

		} else {
			// 签名有误
			System.out.println("签名有误！");
			request.setAttribute(Constant.ERROR_CODE, Constant.EC_PARAM);
			request.setAttribute("tradeRstMessage", "签名有误");
			return "errorPage";
		}

	}


	/**
	 * 验证计算策力请求的sign计算对不对
	 *
	 * @param partnerCode
	 * @param token
	 * @param tradeTime
	 * @param imei
	 * @return
	 */
	private static String requestSign(String partnerCode, String token,
			String tradeTime, String imei) {
		try {
			StringBuffer buffer = new StringBuffer();
			buffer.append("partnerCode=").append(partnerCode);
			buffer.append("&token=").append(token);
			buffer.append("&imei=").append(imei);
			buffer.append("&tradeTime=").append(URLEncoder.encode(tradeTime, "utf-8"));
			System.out.println("策力请求数据加密前的值：" + buffer.toString());
			String result = MD5.calcMD5(buffer.toString());
			System.out.println("策力请求数据加密后的值：" + result);
			return result;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取设备套餐信息
	 *
	 * @param imei
	 * @return
	 */
	@ApiOperation(value = "获取设备套餐信息")
	@RequestMapping(value = "orders")
	public String getOrders(String imei, HttpServletRequest request) {
		if (null == imei || true == imei.isEmpty() || 15 != imei.length()) {
			request.setAttribute(Constant.ERROR_CODE, Constant.EC_PARAM);
			return "errorPage";
		} else {
			return "forward:/module/queryOrder";
		}
	}

	/**
	 * 从套餐列表跳转到套餐详情时使用
	 *
	 * @param index
	 * @param model
	 * @return
	 */
	@ApiOperation(value = "从套餐列表跳转到套餐详情时使用")
	@RequestMapping("packageInfo")
	public String packageInfo(int index, Model model) {
		model.addAttribute("index", index);
		return "monthlyPackageInfo";
	}

	/**
	 * 从订单列表，跳转到订单详情使用
	 *
	 * @param status
	 * @param model
	 * @return
	 */
	@ApiOperation(value = "从订单列表，跳转到订单详情使用")
	@RequestMapping("orderinfo")
	public String orderInfo(int status, Model model) {
		model.addAttribute("status", status);
		if (3 == status) {
			return "orderUnopen";
		} else {
			return "orderUsing";
		}
	}


}
